package utils

import (
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"time"

	"gopkg.in/yaml.v2"
)

func GetHttpUrl(host string, path string) string {
	return "http://" + host + path
}

// 毫秒
func TimeToTimestamp(t *time.Time) int64 {
	return t.UnixNano() / 1e6
}

func TimestampToTime(t int64) time.Time {
	return time.Unix(t/1000, 0)
}

func ReadYamlToMap(file string) (map[string]interface{}, error) {
	res := make(map[string]interface{})

	yamlFile, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	err = yaml.Unmarshal(yamlFile, res)
	if err != nil {
		return nil, err
	}
	log.Println("yaml to map: \n", res)
	return res, nil
}

func IsArchValid(arch string) bool {
	fmt.Println("架构 ", arch)
	if arch != "amd64" && arch != "arm64" {
		return false
	}
	return true
}

func GetIpByDns(dns string) (string, error) {
	var clusterIp string
	fmt.Println("解析dns： ", dns)
	// 解析cname
	cname, _ := net.LookupCNAME(dns)
	// 解析ip地址
	ns, err := net.LookupHost(dns)
	if err != nil {
		fmt.Println("解析dns错误： ", err.Error())
		return "", err
	}
	fmt.Println("cname: ", cname, "ips: ", ns)
	if cname != "" && len(ns) != 0 {
		clusterIp = ns[0]
		fmt.Println("ip: ", clusterIp)
	}
	return clusterIp, nil
}
